package servlets;

import java.io.BufferedReader;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dataBase.Code;
import dataBase.magaers.CodeDBMngr;

/**
 * Servlet implementation class editCode
 */
public class EditCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	CodeDBMngr cdbm;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditCodeServlet() {
        super();
        cdbm = CodeDBMngr.getInstance();
      }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String edit = request.getParameter("edit");
		String cid =  request.getParameter("cid");
		String version =  request.getParameter("version");
		if (edit.equals("edit"))
		{
			BufferedReader reader = request.getReader();
			String code = "";
			String r;
			while ((r = reader.readLine())!= null)
			{
				code += r;
			}
			if(cdbm.duplicatVersion(cid, version, code)){
				response.getOutputStream().print("<html><head><title></title></head><body><h2>Code updated successfully</h2></body></html>");
			}
			else{
				response.sendError(500);				
			}
			return;
		}
		if (edit.equals("delete"))
		{
			if (cdbm.deleteCode(cid, version)){
				response.getOutputStream().print("<html><head><title></title></head><body><h2>Code deleted</h2><p><a href=\"site/search.html\">new search</a></p></body></html>");
			}
			else{
				response.sendError(500);
			}
			return;
		}
		
		if (edit.equals("vis"))
		{
			cdbm.changeVisibility(cid, version);
		}
	}

}
